package com.yuqq.token;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.JwtBuilder;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;

public class JwtTestDemo {

    // 密钥
    private static final String JWT_KEY = "sangeng";
    // 有效期：1小时
    private static final Long JWT_TTL = 60 * 60 * 1000L;

    public static void main(String[] args) {
        try {
            // 生成JWT，包含密码
            String jwt = createJwt("2123", "1234");
            System.out.println("Generated JWT: " + jwt);

            // 解析JWT
            Claims claims = parseJwt(jwt);
            System.out.println("Parsed Claims: " + claims);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成JWT，包含密码
     */
    public static String createJwt(String subject, String password) throws Exception {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        SecretKey secretKey = generateSecretKey();

        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        Date expiration = new Date(nowMillis + JWT_TTL);

        JwtBuilder builder = Jwts.builder()
                .setSubject(subject)
                .claim("password", password)  // 添加密码字段
                .setIssuedAt(now)
                .setExpiration(expiration)
                .signWith(signatureAlgorithm, secretKey);

        return builder.compact();
    }

    /**
     * 解析JWT
     */
    public static Claims parseJwt(String jwt) throws Exception {
        SecretKey secretKey = generateSecretKey();
        Claims claims = Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();

        // 获取密码
        String password = (String) claims.get("password");
        System.out.println("Password from Claims: " + password);

        return claims;
    }

    /**
     * 生成密钥
     */
    private static SecretKey generateSecretKey() {
        byte[] decodedKey = Base64.getDecoder().decode(JWT_KEY);
        return new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
    }
}
